package com.my.blog.website.helper;

import org.springframework.stereotype.Component;

/**
 * @Auther lxf
 * @Date 2021/7/11
 */
@Component
public class HitCacheHelper {

    private final DefaultCacheAdapter<String, Integer> IP_AND_HITS_CACHE = new DefaultCacheAdapter.Builder<String, Integer>()
            .setL1TTLSeconds(300L)
            .setL2TTLSeconds(10 * 60 * 1000)
            .setL1MaxSize(500)
            .setCacheNull(true)
            .setEnableL2(true)
            .setL2KeyPrefix("IP_HITS")
            .setFinalGet(k -> -1)
            .build();

    public Integer getHitsByIpInTenMinutes(String ip) {
        Integer count = IP_AND_HITS_CACHE.get(ip);
        if (count == -1) {
            // 代表该ip第一次访问
            IP_AND_HITS_CACHE.put(ip, 1);
        }
        return count;
    }
}
